package es.and.roid.musichackday;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class MusicHackDayBcn extends Activity implements
		MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
		MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
	/** Called when the activity is first created. */
	private ImageButton playButton = null;
	private EditText InputMp3Source = null;
	private TextView txt_showtime = null;

	private String mp3Source = null;
	private MediaPlayer mp = new MediaPlayer();
	private static final int TIME_BUTTON_INTERVAL = 5;
	private static final String MEDIA_PATH = "/sdcard/";
	static int counterMinutes = 5;
	static int counterSeconds = 00;
	static int speed = 1;

	enum State {
		ZERO, COUNTING, NULL, CLEAR
	};

	State state = State.NULL;
	private Handler mHandler = new Handler();
	private Runnable mUpdateTimeTask = new Runnable() {

		public void run() {
			if (state == State.COUNTING) {
				counterSeconds -= speed;

				printCounter();
				postDelayed();

			}

		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		playButton = (ImageButton) findViewById(R.id.ImageButton01);
		InputMp3Source = (EditText) findViewById(R.id.EditText01);
		txt_showtime = (TextView) findViewById(R.id.TextView01);
		playButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				mp3Source = InputMp3Source.getText().toString();

				if (!mp3Source.equals("")) {

					if (!mp.isPlaying()) {
						if (mp3Source.contains("http://")) {
							// remote
							playStreaming();
						} else {
							// local
							playSong();
						}
					
						// Timer

					} else {
						stopSong();
					}
				}
			}
		});

		txt_showtime.setText(R.string.no_timer);
		ImageButton button = (ImageButton) findViewById(R.id.Button02);

		// Increase the counter
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Log.e("test", "The counter is " + counterMinutes);
				// Maybe start the counter again

				counterMinutes += TIME_BUTTON_INTERVAL;

				printCounter();

			}
		});

		button = (ImageButton) findViewById(R.id.Button01);

		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				state=State.CLEAR;
				counterMinutes = TIME_BUTTON_INTERVAL;
				txt_showtime.setText(R.string.no_timer);
				mHandler.removeCallbacks(mUpdateTimeTask);


			}
		});
	}

	public void stopSong() {
		mp.stop();
		state=State.CLEAR;
		counterMinutes = TIME_BUTTON_INTERVAL;
		counterSeconds= 00;
		txt_showtime.setText(R.string.no_timer);
		mHandler.removeCallbacks(mUpdateTimeTask);
		playButton.setImageResource(android.R.drawable.ic_media_play);
	}

	public static File getFile(Uri uri) {
		if (uri != null) {
			String filepath = uri.getPath();
			if (filepath != null) {
				return new File(filepath);
			}
		}
		return null;
	}

	public void playSong() {
		mp3Source = MEDIA_PATH.concat(mp3Source);
		File aux = new File(mp3Source);
		Log.d("FILE", mp3Source);
		if (aux.exists()) {
			mp.reset();
			try {
				mp.setDataSource(mp3Source);
				mp.prepare();
				mp.start();
				playButton.setImageResource(android.R.drawable.ic_media_pause);
				state=State.COUNTING;
				mHandler.removeCallbacks(mUpdateTimeTask);
				printCounter();
				postDelayed();

			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			// file not found
		}

	}

	private void playStreaming() {
		Uri myUri = Uri.parse(mp3Source);

		if (mp == null) {
			this.mp = new MediaPlayer();
		} else {
			mp.stop();
			mp.reset();
		}
		try {
			mp.setDataSource(this, myUri);
			mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mp.setOnPreparedListener(this);
			mp.setOnBufferingUpdateListener(this);

			mp.setOnErrorListener(this);
			mp.prepareAsync();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // Go to Initialized state

	}

	

	private void stop() {
		mHandler.removeCallbacks(mUpdateTimeTask);
		mp.stop();

	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		stop();

	}
	@Override
	protected void onPause() {
		super.onPause();
		stop();
		
	}
	public void onPrepared(MediaPlayer mp) {
		mp.start();
		playButton.setImageResource(android.R.drawable.ic_media_pause);
		state=State.COUNTING;
		stop();
		printCounter();
		postDelayed();

	}
	public void onCompletion(MediaPlayer mp) {
		stop();
	}

	public boolean onError(MediaPlayer mp, int what, int extra) {
		StringBuilder sb = new StringBuilder();
		sb.append("Media Player Error: ");
		switch (what) {
		case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
			sb.append("Not Valid for Progressive Playback");
			break;
		case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
			sb.append("Server Died");
			break;
		case MediaPlayer.MEDIA_ERROR_UNKNOWN:
			sb.append("Unknown");
			break;
		default:
			sb.append(" Non standard (");
			sb.append(what);
			sb.append(")");
		}
		sb.append(" (" + what + ") ");
		sb.append(extra);
		return true;
	}
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		// TODO Auto-generated method stub

	}

	private void printCounter() {

		if (counterSeconds < 0) {
			counterSeconds = 59;
			counterMinutes -= speed;
		}

		if (counterMinutes < 0) {
			state = State.ZERO;
			counterSeconds = 0;
			counterMinutes = 0;
			// player.stopPlayback();
		}

		String minutesText = String.valueOf(counterMinutes);
		String secondsText = String.valueOf(counterSeconds);
		
		if (minutesText.length() < 2) {
			minutesText = "0" + minutesText;
		}
		if (secondsText.length() < 2) {
			secondsText = "0" + secondsText;
		}

		String counterText = minutesText + ":" + secondsText;
		if (state == State.ZERO) {
			counterText = getString(R.string.no_timer);
			mp.stop();
		}
		txt_showtime.setText(counterText);

	}

	private void postDelayed() {

		mHandler.postDelayed(mUpdateTimeTask, 1000);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.info, menu);
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.menu_info:
	        showAbout();

	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}

	private void showAbout() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.about))
		       .setCancelable(false)
		       .setPositiveButton("Nice!", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.dismiss();
		           }
		       });
		       
		AlertDialog alert = builder.create();
		alert.show();
	}

}